package com._dev.social.service.impl;

import com._dev.social.common.ErrorCode;
import com._dev.social.exception.BusinessException;
import com._dev.social.mapper.UsersMapper;
import com._dev.social.mode.domain.Users;
import com._dev.social.mode.domain.request.UserLoginOrRegisterRequest;
import com._dev.social.service.UsersService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com._dev.social.common.RandomNickName.generate;
import static com._dev.social.contant.UserConstant.DEFAULT_USERNAME;
import static com._dev.social.contant.UserConstant.USER_LOGIN_STATE;

/**
 * @author Administrator
 * @description 针对表【users】的数据库操作Service实现
 * @createDate 2024-11-05 09:45:16
 */
@Service
@Slf4j
@Transactional
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
        implements UsersService {

    @Resource
    private UsersMapper usersMapper;
    //盐值混淆
    private static final String SALT = "social_app";


    @Override
    public Users getSafetyUser(Users originUser) {
        if (Objects.isNull(originUser)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "获取用户失败");
        }

        Users user = new Users();
        user.setId(originUser.getId());
        user.setBio(originUser.getBio());
        user.setEmail(originUser.getEmail());
        user.setUsername(originUser.getUsername());
        user.setNickname(originUser.getNickname());
        user.setImageurl(originUser.getImageurl());
        user.setUid(originUser.getUid());
        return user;
    }

    @Override
    public Users userLogin(String email, String password, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(email, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        String validPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        Matcher matcher = Pattern.compile(validPattern).matcher(email);
        if (!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        //2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //校验用户是否存在
        QueryWrapper<Users> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", email);
        userQueryWrapper.eq("password", encryptPassword);
        Users user = usersMapper.selectOne(userQueryWrapper);
        if (Objects.isNull(user)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        //返回脱敏数据
        Users safetyUser = getSafetyUser(user);
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    @Override
    public void userRegister(UserLoginOrRegisterRequest userRegisterRequest
    ) {

        String email = userRegisterRequest.getEmail();
        String password = userRegisterRequest.getPassword();
        String nickName = userRegisterRequest.getNickName();
        String username = userRegisterRequest.getUsername();
        String bio = userRegisterRequest.getBio();
        String image = userRegisterRequest.getImageUrl();
        if (StringUtils.isAnyBlank(email, password, username, bio)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (username.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户过短");
        }
        if (password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }

        if (bio.equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户简介不能为空");
        }

        String validPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        Matcher matcher = Pattern.compile(validPattern).matcher(email);

// 使用 matches() 来确保整个邮箱格式都符合要求
        if (!matcher.matches()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }

        //判断用户是否重复注册
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("email", email);
        usersQueryWrapper.eq("username", username);
        Users originUser = usersMapper.selectOne(usersQueryWrapper);
        if (Objects.nonNull(originUser)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名和邮箱已经存在,请修改");
        }


        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //插入数据
        Users user = new Users();
        user.setEmail(email);
        user.setPassword(encryptPassword);
        user.setUsername(username);
        if (nickName.isEmpty()) {
            user.setNickname(DEFAULT_USERNAME + generate());
        } else {
            user.setNickname(nickName);
        }
        user.setImageurl(image);
        user.setBio(bio);
        user.setUid(UUID.randomUUID().toString());
        boolean isResult = this.save(user);
        if (!isResult) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "插入失败");
        }
    }

    @Override
    public void updateUserProfileImage(String userId, String imageUrl) {
        Users user = usersMapper.findUserById(userId);
        if (Objects.isNull(user)){
            new BusinessException(ErrorCode.NULL_ERROR, "没有该用户");
        }
        user.setImageurl(imageUrl);
        int rowsAffected = usersMapper.updateById(user);
        if (rowsAffected == 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        //移除登录状态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 0;
    }

    @Override
    public Users findUserById(String uid) {
        Users user = usersMapper.findUserById(uid);
        if (user==null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Users safetyUser = getSafetyUser(user);
        return safetyUser;
    }

    @Override
    public Boolean isExistUser(String uid) {
        Users user = findUserById(uid);
        return Objects.isNull(user);
    }

    @Override
    public List<Users> getListOfUser() {
        List<Users> users = usersMapper.selectList(null);
        for (int i = 0; i < users.size(); i++) {
            users.set(i, getSafetyUser(users.get(i)));
        }
        return users;
    }
}




